function output = lolik_mix(pm2,dt,sts,taus,pis,rn)

% Construct the negative log-likelihood function which is used in the ML
% estimation of the logit model. 

% pm2 is a gx6 vector of parameters, (alpha_g,beta_g,kappa_g,delta_g,gamma_g,lambda_g)
% with an estimated risk parameter, pm2 is a gx7 vector of parameters, (alpha_g,beta_g,kappa_g,delta_g,gamma_g,lambda_g,r_g)

% sts is a vector containing settings (n_types, n_subjects, n_trials) 
% taus is a matrix containing taus for each individual/type

tot_g = sts(1);
tot_n = sts(2);
tot_t = sts(3);

ind_lolik = zeros(tot_n,tot_g);

lo_lik = 0; 

eu=zeros(1,8);
eu2=zeros(1,4);
eu3=zeros(1,4);

alpha=zeros(tot_g);
beta=zeros(tot_g);
kappa=zeros(tot_g);
delta=zeros(tot_g);
gamma=zeros(tot_g);
lambda=zeros(tot_g);
rho=zeros(tot_g);
    
for n = 1:tot_n
for g = 1:tot_g    

    m1 = tot_t*(n-1)+1; m2 = tot_t*n; id = dt(m1,1);   
    subdt = [dt(m1:m2,3:6),dt(m1:m2,7:9),dt(m1:m2,10),dt(m1:m2,11),id*ones(tot_t,1)];    
 
    if rn==2
        alpha(g) = pm2(7*g-6); beta(g) = pm2(7*g-5); kappa(g) = pm2(7*g-4); delta(g)=pm2(7*g-3); gamma(g)=pm2(7*g-2); lambda(g)=pm2(7*g-1);
        rho(g)=pm2(7*g);
    elseif rn==0
        alpha(g) = pm2(6*g-5); beta(g) = pm2(6*g-4); kappa(g) = pm2(6*g-3); delta(g)=pm2(6*g-2); gamma(g)=pm2(6*g-1); lambda(g)=pm2(6*g);
        rho(g)=1;
    else
        alpha(g) = pm2(6*g-5); beta(g) = pm2(6*g-4); kappa(g) = pm2(6*g-3); delta(g)=pm2(6*g-2); gamma(g)=pm2(6*g-1); lambda(g)=pm2(6*g);
        rho(g)=0;
    end 
    
for t = 1:tot_t
    
    theta = subdt(t,1:4); % payoff parameters
    prefs = [alpha(g) beta(g) kappa(g) delta(g) gamma(g)]; % preference parameters
    y = subdt(t,5:7); % beliefs
    choice = subdt(t,8); % strategy  
    game = subdt(t,9); % 1=spd or 2=ug or 3=tg
    
    if game==1
        
        for str = 1:8
            eu(str) = eu_spd(prefs,rho(g),theta,str,y);
        end
        
        ind_lolik(n,g) = ind_lolik(n,g) + (1/lambda(g))*eu(choice)-log(sum(exp((1/lambda(g))*eu)));

    end

    if game==2

        for str = 1:4
            eu2(str) = eu_ug(prefs,rho(g),theta,str,y);
        end
             
        ind_lolik(n,g) = ind_lolik(n,g) + (1/lambda(g))*eu2(choice)-log(sum(exp((1/lambda(g))*eu2)));
        
    end
    
    if game==3
        
        for str = 1:4
            eu3(str) = eu_tg(prefs,rho(g),theta,str,y);
        end
        
        ind_lolik(n,g) = ind_lolik(n,g) + (1/lambda(g))*eu3(choice)-log(sum(exp((1/lambda(g))*eu3)));
       
    end
    
end
    
end
end

for i1 = 1:tot_n
    for j1 = 1:tot_g
        lo_lik = lo_lik + taus(i1,j1)*(log(pis(j1))+ind_lolik(i1,j1));
    end
end

% output is negative log-likelihood ("Q-function")
output = - lo_lik;